#include "SensImg.h"
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <list>
#include <unistd.h>
#include <signal.h>

using namespace::std;

int show_data(Sensor::tsens_data data) {
  std::cout << "x:" << data.x << " ";
  std::cout << "y:" << data.y << " ";
  std::cout << "z:" << data.z << " ";
  std::cout << "keys:" << data.keys << " ";
  std::cout << "timestamp:" << data.timestamp << " ";
  std::cout << "devid:" << data.devid << " ";
  std::cout << "\n";
  return 0;
}

volatile int should_receive;

void ctrlc(int sig) {
  printf("caught SIGINT \n");  
  should_receive = 0;
  printf("receiving should stopp\n");
}

void receive(const list<int> &ports) {
  list<Sensor::SensorReceiver *> sensor_receivers;

  signal(SIGINT, ctrlc);  /* stop receiving on Ctrl-C */
  for(list<int>::const_iterator iter = ports.begin(); 
      iter != ports.end(); 
      iter++) {
    Sensor::SensorReceiver* receiver;
    receiver = new Sensor::SensorReceiver(show_data, *iter);
    sensor_receivers.push_back(receiver);
    std::cout << "starting " << receiver->get_port() << "\n";
  }
  should_receive = 1;
  while (should_receive) {
    sleep(1);
  }
  while (!sensor_receivers.empty()) {
    Sensor::SensorReceiver* receiver = sensor_receivers.back();
    std::cout << "stopping " << receiver->get_port() << "\n";
    delete receiver;
    sensor_receivers.pop_back();
  }
  std::cout << "Receiving stopped\n";
}

int main(int argc, char *argv[]) {
  std::cout << "C++ wrapper for sens_receiver and img_sender\n";
  std::cout << "  receives from all ports on the command line\n";
  if (argc == 1) {
    std::cout << "give the port numbers as command line arguments!\n";
    return 0;
  } else {
    list<int> ports;
    for (int i=1; i < argc; i++) {
      ports.push_back(atoi(argv[i]));
    }
    std::cout << "Receiving on ports ";
    for(list<int>::iterator iter = ports.begin(); iter != ports.end(); iter++) {
      std::cout << *iter << " ";
    }
    std::cout << "\n";
    receive(ports);
  }
  return 0;
}
